﻿using System;
using System.Web.Mvc;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace SimpleForum.Classes.Attributes
{
    public class EmailAttribute : RegularExpressionAttribute, IClientValidatable
    {
        public EmailAttribute() : base("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
        {
            this.ErrorMessage = "The e-mail address is invalid.";
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata MetaData, ControllerContext Cntext)
        {
            yield return new EmailValidationRule(FormatErrorMessage(MetaData.GetDisplayName()));
        }
    }

    public class EmailValidationRule : ModelClientValidationRule
    {
        public EmailValidationRule(string ErrorMessage)
        {
            this.ErrorMessage = ErrorMessage;
            this.ValidationType = "email";
        }
    }
}